package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggin.path}")
    private String basePath;


    //文件的上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        try {
            //1.图片名   UUID+suffix
            String originalFilename = file.getOriginalFilename();//原始图片名称
            log.info("接受到上传的文件:{}", originalFilename);
            //获取原始图片的后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//在最后一个点截取
            //组装新的图片名
            String fileName = UUID.randomUUID().toString() + suffix;
            //2.图片放在什么位置,指定图片位置，如果不存在，创建
            File baseFile = new File(basePath);
            if (!baseFile.exists()) {
                //不存在，创建目录
                baseFile.mkdirs();
            }
            //3.转存
            file.transferTo(new File(basePath + fileName));
            //返回图片的名字
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    //文件的下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info("接收到下载图片的请求：{}", name);

        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(new File(basePath+name));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len=0;
            byte[] bytes = new byte[1024];
            //循环写出
            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关流
            outputStream.close();
            fis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
